// pages/upAddress/upAddress.js
var app = getApp();
var province = "" + 101101; //省
var city = "" + 101101101; //城市
var county = "" + 101101101101; //区县
var provinces = []; //省s
var provinceNames = []; //省名称
var citys = []; //城市s
var cityNames = []; //城市名称
var countys = []; //区县s
var countyNames = []; //区县名称
var value = [0, 0, 0]; //数据位置下标
var addressList = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    transportValues: ["收货时间不限", "周六日/节假日收货", "周一至周五收货"],
    transportIndex: 0,
    provinceIndex: 0, //省份
    cityIndex: 0, //城市
    countyIndex: 0, //区县
    navH: 0,
    user:null,
    address: null,
    array: ['男', '女'],
    index: 0,
    date: '2020-01-01',
    multiArray: [],
    multiIndex: [0, 0, 0]
  },
  onReady: function () {
    var that = this;
    this.dialog = this.selectComponent("#dialog");
  },
  showDialog() {
    var that = this;
    this.dialog.showDialog();
  },
  _cancelEvent() {
    console.log('你点击了取消');
    this.dialog.hideDialog();
  },
  //确认事件
  _confirmEvent() {
    var that = this;
    console.log('你点击了确定');
    wx.request({
      url: app.globalData.url + 'deUserAddress',
      data: {
        addrId: that.data.address.addrId,
        userId: wx.getStorageSync("userId")
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.onShow();
      },
      fail: function (err) {

      },
    })
    this.dialog.hideDialog();
    this.navBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  onLoad: function (options) {
    var that = this
    var id = wx.getStorageSync("userId");
    wx.request({
        url: app.globalData.url + 'getUserByUserId',
        data: {
          userId: id,
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          var user = res.data.data;
          if (user) {
            if(user.sex != 0) {
              user.sex = (user.sex === 1 ? '男' : '女');
            } else {
              user.sex = '';
            }
            if(user.detailAddress){
              let arr = user.detailAddress.split(" ");
              user.detailAddress = arr[arr.length-1];
            }
          }
          

          let address = {
            'province': user.province?user.province:'101101',
            'city': user.city ? user.city : '101101101',
            'district': user.district ? user.district : '101101101101',
          }
          // 更新数据  
          that.setData({
            user: user,
            date: user.memberbirthday,
            address: address,
          });
          that.onloadProvinceData(that.data.address);
      },
      fail: function (err) {

      },
    })
   
    //获取手机高度
    that.setData({
      navH: app.globalData.navHeight,
    })
    
  },
  userSexChange:function(index){
    console.log(index)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  // 获取省份数据
  getProvinceData: function () {
    var that = this;
    var s;
    wx.request({
      url: app.globalData.url + 'getAddressLib', //
      data: {
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        // 更新数据  
        for (var i = 0; i < arr.length; i++) {
          provinceNames[i] = arr[i].province;
          provinces[i] = arr[i].code;
        }
        that.setData({
          provinces: provinces,
          provinceNames: provinceNames
        })
        that.getCityArr(provinces[0]);
      },
      fail: function (err) {

      },
    })
  },
  // 加载获取省份数据
  onloadProvinceData: function (address) {
    var that = this;
    var s;
    wx.request({
      url: app.globalData.url + 'getAddressLib', //
      data: {
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        // 更新数据  
        for (var i = 0; i < arr.length; i++) {
          provinceNames[i] = arr[i].province;
          provinces[i] = arr[i].code;
          if (address.province&&address.province == provinces[i]){
            that.data.multiIndex[0] = i;
            that.setData({
              provinceIndex:i,
              multiIndex: that.data.multiIndex
            })
          }
        }
        that.setData({
          provinces: provinces,
          provinceNames: provinceNames
        })
        that.onloadCityArr(address.province,address.city);
      },
      fail: function (err) {

      },
    })
  },
  // 加载城市数据
  onloadCityArr: function (arr,city) {
    var that = this;
    var c;
    wx.request({
      url: app.globalData.url + 'getAddressCityLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          cityNames[i] = arr[i].city;
          citys[i] = arr[i].code;
          if ((that.data.address.city)&&citys[i] == that.data.address.city){
            that.data.multiIndex[1] = i;
            that.setData({
              cityIndex:i,
              multiIndex: that.data.multiIndex
            })
          }
        }
        // 更新数据  
        that.setData({
          citys: citys,
          cityNames: cityNames,
        })
        that.getCountyInfo(city);
      },
      fail: function (err) {

      },
    })
    if (citys.length == 0) {
      citys[0] = {
        name: ''
      };
      cityNames[0] = {
        name: ''
      };
    }

  },
  // 加载区县数据
  getCountyInfo: function (arr) {
    var that = this;
    var c;
    countys = [];
    countyNames = [];
    wx.request({
      url: app.globalData.url + 'getAddressCountyLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          countyNames[i] = arr[i].district;
          countys[i] = arr[i].code;
          if(countys[i] == that.data.countyIndex){
            that.data.multiIndex[2] = i;
            that.setData({
              countyIndex:i,
              multiIndex: that.data.multiIndex
            })
          }
        }
        // 更新数据  
        that.setData({
          countys: countys,
          countyNames: countyNames
          // value: value,
        })
        that.getMultiArray();
      },
      fail: function (err) {

      },
    })
    if (countys.length == 0) {
      countys[0] = {
        name: ''
      };
      countyNames[0] = {
        name: ''
      };
    };
    var that = this;
    // value = [column0, column1, 0];

    that.setData({
      countys: countys,
      countyNames: countyNames,
      // value: value,
    })

  },

  getCityArr: function (arr, count = 0) {
    var that = this;
    var c;
    wx.request({
      url: app.globalData.url + 'getAddressCityLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          cityNames[i] = arr[i].city;
          citys[i] = arr[i].code;
        }
        // 更新数据  
        that.setData({
          citys: citys,
          cityNames: cityNames,
          cityName: cityNames[0]
        })
        city = citys[0];
        that.getCountyInfo(city, 0);
      },
      fail: function (err) {

      },
    })
    if (citys.length == 0) {
      citys[0] = {
        name: ''
      };
      cityNames[0] = {
        name: ''
      };
    }

  },
  // 获取区县数据
  getCountyInfo: function (arr, column = 0) {
    var c;
    var that = this;
    countys = [];
    countyNames = [];
    wx.request({
      url: app.globalData.url + 'getAddressCountyLib', //
      data: {
        parent: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var arr = res.data.data;
        for (var i = 0; i < arr.length; i++) {
          countyNames[i] = arr[i].district;
          countys[i] = arr[i].code;
        }
        county = countys[0];
        // 更新数据  
        that.setData({
          countys: countys,
          countyNames: countyNames,
          countyName: countyNames[0]
        })
        that.getMultiArray();
      },
      fail: function (err) {

      },
    })
    if (countys.length == 0) {
      countys[0] = {
        name: ''
      };
      countyNames[0] = {
        name: ''
      };
    };
    that.setData({
      countys: countys,
      countyNames: countyNames,
    })

  },

  bindCountyNameChange: function (e) {
    var that = this;
    var val = e.detail.value;
    console.log('picker county 发生选择改变，携带值为', e.detail.value);
    var arr = e.currentTarget.dataset.cou[val];
    county = arr;
    this.setData({
      countyIndex: e.detail.value,
      countyName: that.data.countyNames[e.detail.value],
    })
  },

  saveUserInfo: function (e) {
    var that = this;
    var memberbirthday = e.detail.value.memberbirthday;//生日
    if (memberbirthday == "") {
      wx.showToast({
        title: '生日不能为空',
        icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
        duration: 2000,      //停留时间
      })
      return false;
    }
    var mobile = e.detail.value.mobile;//手机号
    if (!(/^1[3456789]\d{9}$/.test(mobile))) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
        duration: 2000,      //停留时间
      })
      return false;
    }
    var address = e.detail.value.address;//地址
    if (address == "") {
      wx.showToast({
        title: '地址不能为空',
        icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
        duration: 2000,      //停留时间
      })
      return false;
    }
    var provinceName = that.data.multiArray[0][that.data.multiIndex[0]].name;//省
    var cityName = that.data.multiArray[0][that.data.multiIndex[0]].city[that.data.multiIndex[1]].name;//市
    var countyName = that.data.multiArray[0][that.data.multiIndex[0]].city[that.data.multiIndex[1]].areas[that.data.multiIndex[2]].name;//区
    var address = e.detail.value.address;//详细
    if (that.data.defa + "" == "undefined") {
      that.data.defa = e.currentTarget.dataset.def;
    }
    var id = wx.getStorageSync("userId");
    wx.request({
      url: app.globalData.url + 'updateUserByUserId', //
      data: {
        userId: id,
        nickName: e.detail.value.nickName+"",
        realName: e.detail.value.username + "",
        sex: (parseInt(e.detail.value.sex)+1) + "",
        memberbirthday: e.detail.value.memberbirthday + "",
        telephone: mobile,
        province: that.data.multiArray[0][that.data.multiIndex[0]].code,
        city: that.data.multiArray[0][that.data.multiIndex[0]].city[that.data.multiIndex[1]].code,
        district: that.data.multiArray[0][that.data.multiIndex[0]].city[that.data.multiIndex[1]].areas[that.data.multiIndex[2]].code,
        detailAddress: address,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.result == 1) {
          wx.navigateBack({ url: '../userInfo/userInfo' });
        } else if (res.data.result == 0) {
          wx.showToast({
            title: res.data.errmsg,
            icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
            duration: 2000,      //停留时间
          })
        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  switch1Change: function (e) {
    var that = this;
    console.log(e.detail.value)
    that.setData({
      defa: e.detail.value
    })
    console.log('switch1 发生 change 事件，携带值为', e.detail.value)
  },
  navBack: function () {
    var pages = getCurrentPages();
    var beforePage = pages[pages.length - 1];
    beforePage.onShow();
    wx.navigateBack({

    })
  },
  bindMultiPickerColumnChange: function (e) {
    var that = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    if (e.detail.column == 0) {
      that.data.multiIndex = [e.detail.value, 0, 0];
    } else if (e.detail.column == 1) {
      //如果更新的是第二列“市”，第一列“省”的下标不变，第三列“区”的数组下标置为0
      that.data.multiIndex = [that.data.multiIndex[0], e.detail.value, 0];
    } else if (e.detail.column == 2) {
      //如果更新的是第三列“区”，第一列“省”和第二列“市”的值均不变。
      that.data.multiIndex = [that.data.multiIndex[0], that.data.multiIndex[1], e.detail.value];
    }
    if (e.detail.column == 0) {
      var val = e.detail.value;
      var arr = that.data.provinces[val];
      that.getCityArr(arr, val); //获取地级市数据
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    } else if (e.detail.column == 1) {
      var val = e.detail.value;
      var arr = that.data.citys[val];
      that.getCountyInfo(arr, val); //获取区县数据
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    } else if (e.detail.column == 2) {
      this.setData({
        multiIndex: that.data.multiIndex,
      })
    }
  },
  getMultiArray: function () {
    var that = this;
    console.log(that.data.countyNames.length);
    var multiArray = '[';
    for (var i = 0; i < that.data.provinceNames.length; i++) {
      multiArray += '{"city":[';
      for (var j = 0; j < that.data.cityNames.length; j++) {
        multiArray += '{"areas":[';
        for (var k = 0; k < that.data.countyNames.length; k++) {
          multiArray += '{"code":"' + that.data.countys[k] + '","name":"' + that.data.countyNames[k] + '"},';
        }
        multiArray = multiArray.substring(0, multiArray.length - 1);
        multiArray += '],"code":"' + that.data.citys[j] + '","name":"' + that.data.cityNames[j] + '"},';
      }
      multiArray = multiArray.substring(0, multiArray.length - 1);
      multiArray += '],"code":"' + that.data.provinces[i] + '","name":"' + that.data.provinceNames[i] + '"},';
    }
    multiArray = multiArray.substring(0, multiArray.length - 1);
    multiArray += ']';
    var multiArray1 = JSON.parse(multiArray);
    console.log(multiArray1);
    that.setData({
      multiArray: [multiArray1, multiArray1[0].city, multiArray1[0].city[0].areas]
    })
  }
})